import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    cart: JSON.parse(localStorage.getItem('cart') || '[]')
  },
  mutations: {
    //业务逻辑
    addCart (state,addInfo) {
      let flag=false
      state.cart.some(el =>{
        if(el.id === addInfo.id){
          el.count+=addInfo.count
          flag=true
        }
      })
      if(!flag){
        state.cart.push(addInfo)
      }
      localStorage.setItem('cart',JSON.stringify(state.cart))
    }
  },
  actions: {
    addCart ({commit},addInfo) {
      commit('addCart',addInfo)
    }
  },
  getters: {
    getAllCount (state) {
      let all = 0;
      state.cart.some(el=>{
        all+=el.count
      })
      return all
    },
    getAllPrice (state){
      let price = 0
      state.cart.some(el=>{
        if(el.selected===true){
          price+=el.count*el.sell_price
        }
      })
      return price
    }
  },
  modules: {
  }
})

